package com.andy.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.andy.common.constant.ProductConstant;
import com.andy.common.to.SkuHasStockVo;
import com.andy.common.to.SkuReductionTo;
import com.andy.common.to.SpuBoundTo;
import com.andy.common.to.es.SkuEsModel;
import com.andy.common.utils.R;
import com.andy.mall.product.entity.*;
import com.andy.mall.product.feign.CouponFeignService;
import com.andy.mall.product.feign.ElasticSearchFeignService;
import com.andy.mall.product.feign.WareFeignService;
import com.andy.mall.product.service.*;
import com.andy.mall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andy.common.utils.PageUtils;
import com.andy.common.utils.Query;

import com.andy.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ElasticSearchFeignService elasticSearchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuVo(SpuSaveVo saveVo) {
        //1、保存spu基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(saveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2、保存spu描述图片  pms_spu_info_desc
        List<String> decript = saveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3、保存spu图片集    pms_spu_images
        List<String> images = saveVo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(),images);

        //4、保存spu规格参数  pms_product_attr_value
        List<BaseAttrs> attrs = saveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = attrs.stream().map(attr -> {
            ProductAttrValueEntity pave = new ProductAttrValueEntity();
            pave.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            pave.setAttrName(attrEntity.getAttrName());
            pave.setAttrValue(attr.getAttrValues());
            pave.setQuickShow(attr.getShowDesc());
            pave.setSpuId(spuInfoEntity.getId());
            return pave;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);


        //5、保存spu积分信息  mall_sms =>sms_spu_bonuds
        Bounds bounds = saveVo.getBounds();
        SpuBoundTo spuBoundTo=new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode()!= 0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存当前spu对应的Sku信息
        //6.1)、sku的基本信息 pms_sku_info
        List<Skus> skus = saveVo.getSkus();
        if(skus!=null&&skus.size()>0){
            skus.forEach(item->{
                String defaultImage="";
                for (Images img :item.getImages()){
                    if(img.getDefaultImg()==1){  //取出默认图片
                        defaultImage=img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity=new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoService.save(skuInfoEntity);
                //6.2)、sku的图片信息 pms_sku_images
                Long skuId=skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntityList = item.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(
                        entity->{
                            return StringUtils.isNotEmpty(entity.getImgUrl());
                        }
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntityList);
                //6.3)、sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
                //6.4)、sku的优惠、满减等信息 mall_sms => sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //满减金额大于0时才保存
                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }


            });
        }






    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper= new QueryWrapper<SpuInfoEntity>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Override
    public void up(Long spuId) {
        //组装需要的数据
        //1、查出spuId对应的所有sku信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //封装attrs
        //TODO 2.3、查询当前sku所有可以被检索的规格属性
        List<ProductAttrValueEntity> attrsBySpuId = productAttrValueService.getAttrsBySpuId(spuId);
        //收集spuID对应的所有attrId
        List<Long> attrIds = attrsBySpuId.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        //查询出所有的可被检索的attrId
        List<Long> attrSearchIds = attrService.selectSearchAttrIds(attrIds);
        //为了筛选出可被检索的商品attrs
        Set<Long> setAttrIds = new HashSet<>(attrSearchIds);
        //过滤出可被搜索的属性值，并收集成集合。
        List<SkuEsModel.Attrs> attrsList = attrsBySpuId.stream().filter(item -> setAttrIds.contains(item.getAttrId()))
                .map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //TODO 2.4 是否有库存
        Map<Long, Boolean> stockMap = null;//是否有库存stockMap
        try {
            R r= wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){};
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,item->item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
            e.printStackTrace();
        }


        //2、封装每一个Sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);

            // skuPrice skuImg
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());


            //TODO 2.1、热度评分。0
            esModel.setHotScore(0L);

            // brandName brandImg
            //TODO 2.2、查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            //  catalogName
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(category.getName());

            //设置检索属性
            //TODO 2.3 提前查出所有可被检索的属性值，避免循环查询
            esModel.setAttrs(attrsList);

            // hasStock hotScore
            //TODO 2.4 是否有库存
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            return esModel;
        }).collect(Collectors.toList());

            //3、  通过mall-search服务将数据保存到es中

        R r = elasticSearchFeignService.productStatusUp(skuEsModels);

        if(r.getCode()== 0){
            //调用成功
            //4、修改当前Spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //TODO 5、调用失败，重复调用；接口幂等性验证。
        }
    }

}